package com.weiyin.examination.http;


import android.content.Context;

import com.weiyin.examination.http.apiservice.CoolService;

import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * @author njf
 */
public class RetrofitClient {
    public static final String BASE_URL = "http://106.14.199.175:8088";
    private static RetrofitClient retrofitClient;

    private static final int CONNECTION_TIME_OUT = 20;
    private static final int READ_TIME_OUT = 30;
    private static final int WRITE_TIME_OUT = 20;


    private OkHttpClient okHttpClient;
    private CoolService apiService;
    private Context mContext;
    private String baseUrl;

    private RetrofitClient(Context context) {
        this(context, null);
    }

    private RetrofitClient(Context context, String baseUrl) {
        if (StringUtils.isBlank(baseUrl)) {
            this.baseUrl = BASE_URL + "/";
        } else {
            this.baseUrl = baseUrl;
        }
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();

        logging.setLevel(HttpLoggingInterceptor.Level.HEADERS).setLevel(HttpLoggingInterceptor.Level.BODY);
        okHttpClient = new OkHttpClient().newBuilder()
                .connectTimeout(CONNECTION_TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(READ_TIME_OUT, TimeUnit.SECONDS)
                .writeTimeout(WRITE_TIME_OUT, TimeUnit.SECONDS)
                .addInterceptor(logging)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(this.baseUrl)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .build();

        apiService = retrofit.create(CoolService.class);
    }

    public static RetrofitClient getInstance(Context context) {
        if (retrofitClient == null) {
            synchronized (RetrofitClient.class) {
                if (retrofitClient == null) {
                    retrofitClient = new RetrofitClient(context);
                }
            }
        }

        return retrofitClient;
    }

    public static RetrofitClient getInstance(Context context, String baseUrl) {
        return new RetrofitClient(context, baseUrl);
    }

    public CoolService getService() {
        return apiService;
    }
}
